package com.rdc.dictionary.search;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.rdc.dictionary.R;
import com.rdc.dictionary.adapter.WordsAdapter;
import com.rdc.dictionary.adapter.WordsSearchListAdapter;
import com.rdc.dictionary.application.App;
import com.rdc.dictionary.bean.Word;
import com.rdc.dictionary.bean.WordSearch;
import com.rdc.dictionary.mvpBase.BaseMvpActivity;
import com.rdc.dictionary.util.DataBase;
import com.rdc.dictionary.util.WordsAction;

import org.litepal.crud.DataSupport;

import java.util.List;

/**
 * @author Soul Mate
 * @file 文件名
 * @brief 搜索翻译单词句子
 */

public class SearchActivity extends BaseMvpActivity<SearchPresenter, SearchActivityContact.IMainView>
		implements SearchActivityContact.IMainView
{


	private SearchPresenter mPresenter;

	//控件                      音标
	private TextView mWordName,mEnglish,mAmerican, mMeans;
	//mp3
	private ImageButton  mEnglishVoice,mAmericanVoice;

	//搜索栏
	private SearchView mSearchView;

	//空白处
	private LinearLayout mBlank;

	//设置为生词
	private Button mSetNew;

	//布局（显示）
	private LinearLayout mShow;


	@Override
	public void onCreate(Bundle savedInstanceState)
	{

		super.onCreate(savedInstanceState);

		//接收生词本传入的单词并显示
		Intent intent = getIntent();
		if(intent.getSerializableExtra("word_data")!=null)
		{
			Word word = (Word) intent.getSerializableExtra("word_data");
			//显示
			show(word);

			//更新model持有的Word
			mPresenter.updateModel(word);
		}

		//显示搜索记录
		setSearchList();


		//监听搜索框
		mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

			@Override public boolean onQueryTextSubmit(String query)
			{
				//传入需要搜索单词
				mPresenter.searchWord(WordsAction.getAddressForWords(query));

				//查重
				if(DataBase.check(query))
				{
				} else
				//保存到搜索记录的数据库
				mPresenter.saveSearch(query);

				//显示搜索记录
				setSearchList();

				return true;
			}

			@Override public boolean onQueryTextChange(String newText)
			{
				return false;
			}
		});

		//监听播放
		mEnglishVoice.setOnClickListener(new View.OnClickListener()
		{
			@Override public void onClick(View v)
			{
				mPresenter.playMP3("E");
			}
		});

		mAmericanVoice.setOnClickListener(new View.OnClickListener()
		{
			@Override public void onClick(View v)
			{
				mPresenter.playMP3("A");
			}
		});


		//监听添加生词到数据库
		mSetNew.setOnClickListener(new View.OnClickListener()
		{
			@Override public void onClick(View v)
			{
				//检查是否重复
				if(mPresenter.checkRepetition())
				{
					Toast.makeText(App.sContext, "生词已在生词本，请勿重复添加", Toast.LENGTH_SHORT).show();
				}else
				{
					//保存mp3
					mPresenter.saveMP3();
					mPresenter.saveWordTODataBase();

					Toast.makeText(App.sContext, "添加成功", Toast.LENGTH_SHORT).show();

				}
			}
		});



	}



	@Override public void onDestroy(Bundle savedInstanceState)
	{

	}

	@Override
	protected SearchPresenter CreatePresenter() {
		return new SearchPresenter();
	}

	@Override
	protected void init()
	{
		//获取UI控件
		mAmerican = findViewById(R.id.tv_A);
		mAmericanVoice = findViewById(R.id.iv_A);
		mEnglishVoice = findViewById(R.id.iv_E);
		mEnglish = findViewById(R.id.tv_E);
		mMeans = findViewById(R.id.tv_means);
		mWordName = findViewById(R.id.tv_word);
		mSearchView = findViewById(R.id.sv_search);
		mSetNew = findViewById(R.id.bt_new);
		mShow = findViewById(R.id.ll_show);

		//点击输入框外实现软键盘隐藏
		mBlank = findViewById(R.id.ll_fatherLayout);
		mBlank.setOnClickListener(new View.OnClickListener() {
			@TargetApi(Build.VERSION_CODES.CUPCAKE) @Override
			public void onClick(View v)
			{
				InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
				inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
			}
		});



		//初始化presenter
		mPresenter = getPresenter();
		mPresenter.init();




	}

	@Override
	protected int getLayoutResId() {
		return R.layout.activity_search;
	}


	/**
	 * 呈现搜索结果
	 */
	@Override
	public void show(Word word)
	{

			mShow.setVisibility(View.VISIBLE);
			mWordName.setText(word.getWord());
			mEnglish.setText(String.format(getResources().getString(R.string.psE), word.getE()));
			mAmerican.setText(String.format(getResources().getString(R.string.psA), word.getA()));
			mMeans.setText(word.getMeans());

	}



	public void setSearchList()
	{
		//获取数据库中的搜索记录
		List<WordSearch> wordSearchList = DataSupport.findAll(WordSearch.class);

		//recycleView的操作
		RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_searchList);
		//瀑布流  数字为设置的列数
		StaggeredGridLayoutManager layoutManager = new
				StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
		recyclerView.setLayoutManager(layoutManager);

		layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
		recyclerView.setLayoutManager(layoutManager);

		//new Adapter的同时设置监听
		WordsSearchListAdapter adapter = new WordsSearchListAdapter(wordSearchList, new WordsSearchListAdapter.OnItemClickListener()
		{
			//搜索
			@Override public void onClickSearch(int pos)
			{
				String word = wordSearchList.get(pos).getName();
				mPresenter.searchWord(WordsAction.getAddressForWords(word));
			}

			//删除
			@Override public void onClickDelete(int pos)
			{
				//获取要删除的单词
				String search  = wordSearchList.get(pos).getName();
				//删除单词名为search的一行
				DataSupport.deleteAll(WordSearch.class, "name = ?",search );
				//重新加载搜索记录
				setSearchList();

			}
		});
		recyclerView.setAdapter(adapter);

	}



}


